#include "server.hpp"

void user_mandb()
{
    std::cout << "error command, please input like:  \"./server port\" " << std::endl;
    exit(0);
}

string judge_get_road(string &suffix)
{
    string ct = "Content-Type:";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";

    ct += "\r\n";
    return ct;
}

void http_message_deal(http_request &req, http_response &resp)
{
    cout << "--------------------start---------------" << endl;
    cout << req._method << endl;
    cout << req._url << endl;
    cout << req._http_version << endl;
    cout << "--------------------end---------------" << endl;

    string resp_line = "HTTP/1.1 200 OK\r\n";

    // if(req._path == "test.py")
    // {
    //     //建立进程间通信，pipe
    //     //fork创建子进程，execl("/bin/python", test.py)
    //     // 父进程，将req.parm 通过管道写给某些后端语言，py，java，php等语言
    // }
    // if(req.path == "/search")
    // {
    //     // req.parm
    //     // 使用我们自己写的C++的方法，提供服务
    // }

    string resp_head = judge_get_road(req._suffix);

    string body;
    body.resize(req._size);

    resp_head += "Content-Length: ";
    resp_head += std::to_string(req._size);
    resp_head += "\r\n";

    string resp_blank = "\r\n";

    if (!Util::ReadFile(req._path, (char *)body.c_str(), req._size))
    {
        Util::ReadFile(html_404, (char *)body.c_str(), req._size);
    }

    body += "\r\n";

    resp._outbuff += resp_line;
    resp._outbuff += resp_head;
    resp._outbuff += resp_blank;
    resp._outbuff += body;

}

int main(int args, char *argc[])
{
    if (args != 2)
    {
        user_mandb();
    }

    http_server *server = new http_server(atoi(argc[1]), http_message_deal);
    server->server_init();
    server->server_start();

    delete server;
    return 0;
}
